<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../style.css" type="text/css" />
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
</head>
<?php
		include_once "../inc/docroot.php";
		include_once PATH."inc/class.autores.inc.php";
		require PATH."inc/google-api-php-client-master/autoload.php";
		require_once '../../scheduler/sender/lib/class.phpmailer.php';
		$autores = new autores($db);
		if(isset($_GET['alias']))$alias_id = $_GET['alias'];
		if(isset($_GET['edit']))$edit = $_GET['edit'];
		if(isset($_GET['delete']))$delete = $_GET['delete'];
		if(isset($_GET['campaign']))$campaign_id = $_GET['campaign'];
		else if(isset($_GET['state']))$campaign_id = $_GET['state'];

		//getch needed info
        $client_info = $autores->getClientInfo();
        $client_id = $client_info['client_id'];
        $client_secret = $client_info['client_secret'];
        $redirect_uri = $client_info['alias_redirect'];

        //init google client
        $client = new Google_Client();
        $client->setClientId($client_id);
        $client->setClientSecret($client_secret);
        $client->setRedirectUri($redirect_uri);

        $client->addScope("https://mail.google.com");
        $client->setApprovalPrompt('force');
        $client->setAccessType('offline');
        
        if(isset($campaign_id)){
            $client->setState($campaign_id);
        }
        
        //init google service
        $service = new Google_Service_Gmail($client);
        
        if (isset($_REQUEST['logout'])) {
            unset($_SESSION['access_token']);
        }

        if (isset($_GET['code']) && !$client->getAccessToken()) { // we received the positive auth callback, get the token and store it in session
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
        }
        
        if($client->getAccessToken() && $client->isAccessTokenExpired()){
            $client->refreshToken($_SESSION['access_token']);
            $_SESSION['access_token'] = $client->getAccessToken();
        }
        
        if (isset($_SESSION['access_token']) && $client->getAccessToken()) { // extract token from session and configure client
            $access_token = $client->getAccessToken();
            $profile = $service->users->getProfile('me');
            
            echo "<div align=\"center\">";
            echo "<br/>";
            $autores->editalias($profile->emailAddress, $_SESSION['access_token']);
            echo "<br/>";
            $autores->editsubmaster($profile->emailAddress, $_SESSION['access_token']);
            echo "</div>";

            if(!$autores->verifiedSender($profile->emailAddress)){
                //send test mail
                //fgasdg egfdsfgdsfgdfg
                //echo "<script>alert('authenticate again');</script>";
                
                //if(isset($_SESSION['access_token']))unset($_SESSION['access_token']);
                $mails = array('Digginsydw876@gmail.com', 'gonzalezshopia@yahoo.com', 'gonzalezshopia@hotmail.com', 'mesba.cit06@yahoo.com');
                //$mails = array('nobody@gmail.com');
                for($i=0;$i<10;$i++){
                    $mail = new PHPMailer();
                    $mail->CharSet = "UTF-8";
                    $subject = "Test mail";
                    $msg = "Test sending mail.";
                    $mail->AddAddress($mails[$i%count($mails)]);
                    $mail->AddReplyTo($profile->emailAddress);
                    $mail->Subject = $subject;
                    $mail->Body    = $msg;
                    
                    $m = new Google_Service_Gmail_Message();
                    
                    $mail->preSend();
                    $mime = $mail->getSentMIMEMessage();
                    $data = base64_encode($mime);
                    $data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
                    $m->setRaw($data);
                    $service->users_messages->send('me', $m);
                }

                sleep(30);
                
               // authenticate again
               // unset($_SESSION);
               // unset($_GET);
               // unset($_REQUEST);
                
                //$_GET['code'] = "";
                
                if (isset($_SERVER['HTTP_COOKIE']) && false) {
                    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
                    foreach($cookies as $cookie) {
                        $parts = explode('=', $cookie);
                        $name = trim($parts[0]);
                        setcookie($name, '', time()-1000);
                        setcookie($name, '', time()-1000, '/');
                    }
                }
                
                $nclient = new Google_Client();
                $nclient->setClientId($client_id);
                $nclient->setClientSecret($client_secret);
                $nclient->setRedirectUri($redirect_uri);

                $nclient->addScope("https://mail.google.com");
                $nclient->setApprovalPrompt('force');
                $nclient->setAccessType('offline');
                if(isset($campaign_id)){
                    $nclient->setState($campaign_id);
                }
                
                $nservice = new Google_Service_Gmail($nclient);
                
                $nclient->setLoginHint($profile->emailAddress);
                $nloginUrl = $nclient->createAuthUrl();
                //echo $loginUrl;
                //unset($_SESSION['access_token']);
                header('Location: ' . filter_var($nloginUrl, FILTER_VALIDATE_URL));
            }
            else {
                $logoutUrl = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=";
                $logoutUrl = $logoutUrl . $redirect_uri . "?state=" . $campaign_id;
                header('Location: ' . filter_var($logoutUrl, FILTER_VALIDATE_URL));
            }
            
            //if(isset($_SESSION['access_token']))unset($_SESSION['access_token']);
            //if(isset($_GET['code']))unset($_GET['code']);
        }
?>

<body>
<div>
   <div class="autores_header">
<?php
       	if(  !empty($_POST['name']) &&!empty($_POST['mailid']) && !empty($_POST['password']) && !empty($_POST['smtp']) && !empty($_POST['imap']) && isset($alias_id) && isset($edit) && $edit == 1) {
        	echo "<br /><br />";
            $complain = $autores->isPossibleAddAlias($campaign_id, $_POST['mailid'], $alias_id);
            if($complain == "" ){
                echo $autores->editalias($alias_id);
                
                $gmail = "@gmail.com";
                if(strstr($_POST['mailid'],$gmail)!=false)
                {
                    $client->setLoginHint($_POST['mailid']);
                    $loginUrl = $client->createAuthUrl();
                    header('Location: ' . filter_var($loginUrl, FILTER_VALIDATE_URL));
                }
                else {
                ?>
                    <script>
                        window.opener.location.reload();
                    </script>
                <?php
                }
           }
           else echo $complain;
	   }
	   else if(isset($alias_id) && isset($delete) && $delete == 1) {
        	echo "<br /><br />";
			echo $autores->deletealias($alias_id);
			?>
			<script>
			window.opener.location.reload();
			window.close();
            </script>
            <?php
	   }
	   
	   else if( !empty($_POST['name']) &&!empty($_POST['mailid']) && !empty($_POST['password']) && !empty($_POST['smtp']) && !empty($_POST['imap'])) {
        	echo "<br /><br />";
        	$complain = $autores->isPossibleAddAlias($campaign_id, $_POST['mailid']);
            if($complain == "" ){
                if (isset($_SERVER['HTTP_COOKIE']) && false) {
                    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
                    foreach($cookies as $cookie) {
                        $parts = explode('=', $cookie);
                        $name = trim($parts[0]);
                        setcookie($name, '', time()-1000);
                        setcookie($name, '', time()-1000, '/');
                    }
                }
                echo $autores->addalias($campaign_id);
                
                $gmail = "@gmail.com";
                if(strstr($_POST['mailid'],$gmail)!=false)
                {
                    $client->setLoginHint($_POST['mailid']);
                    $loginUrl = $client->createAuthUrl();
                    header('Location: ' . filter_var($loginUrl, FILTER_VALIDATE_URL));
                }
                else {
                ?>
                    <script>
                        window.opener.location.reload();
                    </script>
                <?php
                }
            }
            else echo $complain;
	   }
	   else{
    	echo "<br />";
    	echo "<br />";
		if(!isset($delete))
   			echo "<label>Please fill all the fields.</label>";
	}
    echo "<br />";
   	echo "<br />";
   
	if(isset($campaign_id) && isset($alias_id) && isset($edit) && $edit == 0){
		echo "<label>EDIT SENDER MAIL: " .$alias_id."</label>";
	}
	else if(isset($campaign_id) && isset($alias_id) && isset($delete) && $delete == 0){
		echo "<label> Are you sure to DELETE Sender Mail: " .$alias_id."</label>";
		echo "<br/>";
		echo "<br/> <br/>";
	?>
    
   <form method="post" action="addnewalias.php<?php if(isset($alias_id) && isset($delete)) echo "?alias=".$alias_id."&delete=1";?>" name="deletealias" id="deletealias">
  <br /><br />
  <input type="submit" name="deletealias" id="deletealias" value="DELETE SENDER MAIL" class="btn btn--blue btn--m" />
	</div>
	<?php
    }
	else {
    	echo "<label>ADD A NEW SENDER</label>";
	}
	if(!isset($delete)){
?>
  </div>
    
  <form method="post" action="addnewalias.php<?php echo "?campaign=".$campaign_id;?><?php if(isset($alias_id) && isset($edit)) echo "&alias=".$alias_id."&edit=1";?>" name="addaliasform" id="addaliasform">
    <div style="font-size:9px;" align="center">
    <br />
      <br />
      <input type="text" name="name" id="name" style="text-align:center"/>
      <label for="name">Name</label>
      <br />
      <br />
      <input type="text" name="mailid" id="mailid" style="text-align:center"/>
      <label for="mailid">Email ID</label>
      <br />
      <br />
      <input type="text" name="password" id="password" style="text-align:center"/>
      <label for="password">Password</label>
      <br />
      <br />
      <select name="smtp" id="smtp" width="340" style="width: 340px; height:20px; font-size:13px;" height="20">
<?php 
		$autores->smtpselect();
?>
      </select></br>
      <label for="smtp">SMTP</label>
      <br />
      <br />
      <select name="imap" id="imap" width="340" style="width: 340px; height:20px; font-size:13px;" height="20">
<?php 
		$autores->imapselect();
?>
      </select></br>
      <label for="imap">IMAP</label>
      <br />
      <br />
      <br />
      <br/ >
      <input type="submit" name="addaliasinput" id="addaliasinput" value="Save Sender Mail" class="btn btn--blue btn--m" />
    </div>
  </form>
  <?php } ?>
</div>
</body>
